package ua.keeper.query;

import java.lang.Object;
import java.util.ArrayList;
import java.util.List;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class TPList extends Object
{
    private SQLiteDatabase db_;
    
    protected class TPsingle extends Object
    {
    	private String title_;
    	private String id_;
    	
    	TPsingle (String id, String title)
    	{
    		id_ = new String();
    		title_ = new String();
    		setId(id);
    		setTitle(title);
    	}
    	
    	public void setId(String newId)
    	{
    		id_ = newId;
    	}
    	
    	public void setTitle(String newTitle)
    	{
    		Log.w("TPsingle.setTitle", newTitle);
    		title_ = newTitle;
    	}
    	
    	public String getId()
    	{
    		return id_;
    	}
    	
    	public String getTitle()
    	{
    		return title_;
    	}
    };
    
    List<TPsingle> listItems_;
    
    /*****************************************************************************************/
    TPList(SQLiteDatabase dataBase)
    {
    	db_ = dataBase;
    	if (!db_.isOpen())
    	{
    		Log.w("TPList.Init()", "DataBase is not opened!");
    		return;
    	}
    	Cursor cursor = db_.rawQuery("SELECT rowid, title FROM tp_list WHERE rowid > ?", new String[] { "0" });
    	
    	listItems_ = new ArrayList<TPsingle>();
        while(cursor.moveToNext())
        {
        	TPsingle tp = new TPsingle(cursor.getString(0), cursor.getString(1));
        	listItems_.add(tp);
        }
        cursor.close();
    }
    /*****************************************************************************************/
    public String getTitleById(String id)
    {
    	if (!db_.isOpen())
    	{
    		Log.w("TPList.getTitleById()", "DataBase is not opened!");
    		return "<error>";
    	}
    	Cursor cursor = db_.rawQuery("SELECT title FROM tp_list WHERE rowid = ?", new String[] { id });
    	if (cursor.getCount() == 0)
    	{
    		Log.w("TPList.getTitleById()", "Cursor is empty!");
    		cursor.close();
    		return "<error>";
    	}
    	cursor.moveToFirst();
    	String ans = cursor.getString(0);
    	cursor.close();
    	return ans;
    }
    /*****************************************************************************************/
    public CharSequence[] getIdArray()
    {
    	CharSequence[] ans = new CharSequence[listItems_.size()];
    	for (int it = 0; it < listItems_.size(); it++)
    	{
    		ans[it] = listItems_.get(it).getId();
    	}
    	return ans;
    }
    
    /*****************************************************************************************/
    public CharSequence[] getTitleArray()
    {
    	CharSequence[] ans = new CharSequence[listItems_.size()];
    	for (int it = 0; it < listItems_.size(); it++)
    	{
    		ans[it] = listItems_.get(it).getTitle();
    	}
    	return ans;
    }
}

